package com.flute.icrawler.app.processor.extractor.special;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flute.icrawler.app.entity.CrawlResult;
import com.flute.icrawler.app.util.ParameterKey;
import com.flute.icrawler.framework.framework.CrawlUrl;
import com.flute.icrawler.framework.processor.result.ResultParameter;

/**
 * 优酷视频评论的链接获取方式
 * 
 * @author jiangbo
 * 
 */
public class YouKuCommentAlgo implements IExtractorBelongingsAlgo {

	private static final Logger LOGGER = LoggerFactory
			.getLogger(YouKuCommentAlgo.class);

	/**
	 * @param args
	 */

	public final static void main(String[] args) throws Exception {

		// System.out.println("11#11".replaceFirst("#", "@"));

		String[] strings = new String[3];
		strings[0] = "XMjI5NTE0NjMy";
		strings[1] = "1292304723";

		System.out.println(replaceParas(getCommentTemplate(), strings));

		String str = "name=\"span_detailcommenttotal\">767</span>";
		System.out.println(getMaxPage(str));

		CrawlUrl crawlUrl = new CrawlUrl(null,
				"http://v.youku.com/v_show/id_XMjI5NTE0NjMy.html");

		String[] url = new YouKuCommentAlgo().extractor(crawlUrl);
		System.out.println("该视频评论页：" + url);

	}

	@Override
	public String[] extractor(CrawlUrl crawlUrl) {

		// TODO Auto-generated method stub
		ResultParameter parameter = crawlUrl
				.getResultParameter(ParameterKey.RESULT_CRAWL);
		if (null == parameter) {
			LOGGER.error("parameter is null url=" + crawlUrl.getUrl());
			return null;
		}
		CrawlResult result = (CrawlResult) parameter.getValue();

		String content = "";
		// 是期望的类型
		if (isExpectedType(result.getContentType(),
				ParameterKey.CONTENTTYPE_HTML)) {

			try {
				content = new String(result.getContent(), result.getCharSet());
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		// 填写视频ID 和时间戳
		String[] paras = { getVideoID(content), getTimeStr(content) };

		// 获得未取得分页信息的链接
		String commentNoPage = replaceParas(getCommentTemplate(), paras);

		int pages = getMaxPage(content);

		String[] comments = new String[pages];
		for (int i = 1; i <= pages; i++) {
			String[] paraPage = { "" + i };
			comments[i - 1] = replaceParas(commentNoPage, paraPage);
		}

		return comments;
	}

	public static String getCommentTemplate() {
		return "http://v.youku.com/v_vpcommentContent/id_#_time_#_page_#.html?__rt=1&__ro=videobodycommentlist";
	}

	/**
	 * 填写模板中需要的参数
	 * 
	 * @param originalURL
	 *            链接格式模板
	 * @param paras
	 *            链接中动态的参数
	 * @return
	 */
	private static String replaceParas(String originalURL, String[] paras) {

		for (int i = 0; i < paras.length; i++) {
			String para = paras[i];
			if (null == para) {
				break;
			}
			originalURL = originalURL.replaceFirst("#", paras[i]);
		}

		return originalURL;

	}

	private String getVideoID(String strContent) {

		// String regEx = "var videoId2= 'XMjI5NTE0NjMy';";
		String regEx = "var videoId2= '(.*)';";

		Pattern p = Pattern.compile(regEx);
		Matcher matcher = p.matcher(strContent);
		if (matcher.find()) {
			return matcher.group(1);
		}
		return "";

	}

	private String getTimeStr(String strContent) {
		String regEx = "//nova_update\\('videobodycommentlist'\\, '/v_vpcommentContent/id_'\\+videoId\\+'_time_(.*)'\\);";
		Pattern p = Pattern.compile(regEx);
		Matcher matcher = p.matcher(strContent);
		if (matcher.find()) {
			return matcher.group(1);
		}
		return "";

	}

	/**
	 * 获取可以出现的最大页数
	 * 
	 * @param strContent
	 * @return
	 */
	private static int getMaxPage(String strContent) {
		int page = 1;
		String regEx = "name=\"span_detailcommenttotal\">(\\d+)</span>";
		Pattern p = Pattern.compile(regEx);
		Matcher matcher = p.matcher(strContent);
		if (matcher.find()) {
			// 总的评论条数
			int totalComments = Integer.parseInt(matcher.group(1));
			// 每页显示30条
			page = totalComments / 30 + 1;

		}
		return page;
	}

	private boolean isExpectedType(String contentType, String[] expectedPrefixs) {

		for (int i = 0; i < expectedPrefixs.length; i++) {

			if (isExpectedType(contentType, expectedPrefixs[i])) {
				return true;
			}
		}
		return false;
	}

	private boolean isExpectedType(String contentType, String expectedPrefix) {

		return contentType != null
				&& contentType.toLowerCase().startsWith(expectedPrefix);
	}

}
